package com.hllxd.hism.star.util;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;

/**
 *
 */
@Slf4j public class CounterLogger {

    private static Logger counter = LoggerFactory.getLogger("counterLogger");

    // 定义输出结构
    @Data static class LogDef {
        private String traceID;
        private String reqUri;
        private String userID;
        private String startTime;
        private String localIP;
        private String remoteIP;
        private String callType;
        private long processMs;
        private int resultCode;
        private int responseSize;
        private int requestSize;
    }

    public static void write(HttpServletResponse response, String reqUri) {
        ConsoleContext context = ThreadLocalManager.getConsoleContext();
        if(null==context){
            return;
        }
        long beginMs = context.getBeginMs();
        HttpServletRequest request = context.getRequest();
        LogDef logDef = new LogDef();
        logDef.setReqUri(reqUri);
//        logDef.setReqID(context.getReqId());
        logDef.setTraceID(context.getTraceId());
        logDef.setStartTime(TraceUtil.time("yyyyMMddHHmmssSSS", beginMs));
        logDef.setCallType("http");
        logDef.setLocalIP(getLocalIp());

        // 需要通过函数获取对端的IP地址
        // 在内部基本上不需要太多
        logDef.setRemoteIP(getHttpIp(request));//response.();
        logDef.setProcessMs(System.currentTimeMillis() - beginMs);//response.getProcessMs();
        logDef.setResultCode(response.getStatus());
        logDef.setResponseSize(response.getBufferSize());
        logDef.setRequestSize(request.getContentLength());
        counter.info("{}", JSON.toJSONString(logDef));
    }

    private static String getLocalIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            log.error("get local host failed.[{}]", e.toString());
            return null;
        }
    }

    public static String getHttpIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
